const {generateSha1ByBasename} = require("../../util/hash");
const markdownItWikiLinkEnhanced = (md) => {
    // 存储文档映射，用于解析复杂的链接关系
    const docMap = {};

    md.inline.ruler.before('link', 'wikilink', function(state, silent) {
        const max = state.posMax;
        const start = state.pos;

        if (state.src.charCodeAt(start) !== 0x5B ||
            state.src.charCodeAt(start + 1) !== 0x5B) {
            return false;
        }

        let pos = start + 2;
        let depth = 1;
        let contentStart = pos;

        // 支持嵌套的括号（虽然Obsidian中不常见，但更健壮）
        while (pos < max) {
            const char = state.src.charCodeAt(pos);

            if (char === 0x5B) { // [
                depth++;
            } else if (char === 0x5D) { // ]
                if (pos + 1 < max && state.src.charCodeAt(pos + 1) === 0x5D) {
                    depth--;
                    if (depth === 0) {
                        const content = state.src.slice(contentStart, pos);

                        if (!silent) {
                            const token = state.push('wikilink', '', 0);

                            // 解析链接和锚点 [[文档#标题]]
                            if (content.includes('#')) {
                                const [doc, anchor] = content.split('#');
                                token.content = doc.trim();
                                token.info = content; // 保持完整信息
                                token.attrs = [
                                    ['href', `${doc.trim().replace(/\s+/g, '-')}#${anchor}`],
                                    ['class', 'wiki-link'],
                                    ['data-anchor', anchor]
                                ];
                            } else {
                                token.content = content;
                                token.info = content;
                                token.attrs = [
                                    ['href', `${content.replace(/\s+/g, '-')}`],
                                    ['class', 'wiki-link']
                                ];
                            }
                        }

                        state.pos = pos + 2;
                        return true;
                    }
                }
            }
            pos++;
        }
        return false;
    });

    md.renderer.rules.wikilink = function(tokens, idx) {
        const token = tokens[idx];
        const displayText = token.info || token.content;
        const anchorRegex = /^#\^(\d+)\|.*?\^\1$/;
        if (displayText.match(anchorRegex)) {
            // 如果是一个anchor如：#^4|16位段寄存器^4
            return `<span>${displayText}</span>`;
        } else {
            const href = token.attrs.find(attr => attr[0] === 'href')[1];
            const hrefHash = generateSha1ByBasename(displayText);
            const className = token.attrs.find(attr => attr[0] === 'class')[1];

            return `<a href="${hrefHash}#~:~hint=${displayText}" class="${className}">${displayText}</a>`;
        }
    };


}

module.exports = markdownItWikiLinkEnhanced;